<template>
	<!-- 运营系统-回传监测配置 -->
	<d2-container class="d-flex flex-column mod-sys__user">
		<template v-if="$hasPermission('playlet:dataBackhaulSetting:index')">
			<div class="d-flex b-s mt-2 mb-10 j-sb" slot="header">
				<el-form class="d-flex b-s" :inline="true" size="small" :model="dataForm"
					@keyup.enter.native="getTableList(true)" @submit.native.prevent>
					<el-form-item label="配置名称">
						<el-input v-model="dataForm.keyword" placeholder="配置名称" clearable />
					</el-form-item>
					<el-form-item label="选择公司">
						<el-select clearable v-model="dataForm.company_id" placeholder="请选择公司" @focus="companyFocusFn(false)" @clear='clearCompanyFn' @change='clearCompanyFn'>
							<el-option v-for="(item,index) in companyName" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item v-if="dataForm.company_id" label="选择小程序">
						<el-select clearable v-model="dataForm.applet_id" placeholder="请选择小程序" @focus="getAppletFn">
							<el-option v-for="(item,index) in appletList" :key="index" :label="item.label" :value="parseInt(item.value)"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button icon="el-icon-search" type="primary"
							@click="getTableList(true)">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="success" icon="el-icon-circle-plus-outline" v-show="$hasPermission('playlet:dataBackhaulSetting:create')"
							@click="addOrUpdateData()">添加配置模板</el-button>
					</el-form-item>
				</el-form>
				<div class="d-flex">
					<vxe-toolbar ref="toolbarRef" custom :refresh="{ queryMethod: getTableList,code:'query' }"></vxe-toolbar>
				</div>
			</div>
			<vxe-table ref="dataBackhaulSettingTable" key="dataBackhaulSettingTable" border height="100%" resizable size="medium"
				:loading="tableLoading" :loading-config="{icon: 'vxe-icon-indicator roll', text: '正在拼命加载中...'}"
				:data="dataList">
				<vxe-column width="100" field="id" title="配置ID" sortable align="center"></vxe-column>
				<vxe-column width="180" field="name" title="配置名称" align="center"></vxe-column>
				<vxe-column header-class-name="playlet_dataBackhaulSetting_aname" width="150" field="applet_name" title="小程序名称" align="center"
				:filters="appletFilters" :filter-method="filterApplet"></vxe-column>
				<!-- <vxe-column width="220" field="spread_plaform_id" title="投放平台ID" align="center"></vxe-column> -->
				<vxe-column width="180" field="spread_platform_name" title="投放平台名字" align="center"></vxe-column>
				<vxe-column width="150" field="company_name" title="公司名称" align="center"></vxe-column>
				<vxe-column width="160" field="created_at" title="创建时间" sortable cell-type="string" align="center"></vxe-column>
				<vxe-column width="160" field="updated_at" title="修改时间" sortable cell-type="string" align="center"></vxe-column>
				<vxe-column v-if="!tableLoading||(dataList.length&&$hasPermissionNum(['playlet:dataBackhaulSetting:update','playlet:dataBackhaulSetting:delete']))"
				title="操作" fixed="right" :width="$hasPermissionNum(['playlet:dataBackhaulSetting:update','playlet:dataBackhaulSetting:delete'])*100" align="center" cell-class-name="py-10">
					<template v-slot="{ row }">
						<el-button size="small" round icon="el-icon-edit"
						v-if="$hasPermission('playlet:dataBackhaulSetting:update')"
						@click="addOrUpdateData(row)" type="primary">编辑</el-button>
						<el-button size="small" round icon="el-icon-delete"
						v-if="$hasPermission('playlet:dataBackhaulSetting:delete')"
						@click="deleteHandleSetter(row)" type="danger">删除</el-button>
					</template>
				</vxe-column>
				<template #empty>
					<div class="d-flex flex-row a-center j-center font-md">
						<div class="d-flex">
							暂时没有数据~
						</div>
					</div>
				</template>
			</vxe-table>
			<!-- 分页 -->
			<div class="d-flex" slot="footer">
				<vxe-pager background size="medium" align="right" :border="false" :current-page="dataForm.page"
					:page-size="dataForm.pageSize" :total="total" :pageSizes="[20,50,100,150,200]"
					:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
					@page-change="handlePageChange">
				</vxe-pager>
			</div>
			<!-- 新增/修改弹窗 -->
			<dataBackhaulSetting-add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateDialog" @refreshDataList="getTableList"></dataBackhaulSetting-add-or-update>
			<dataBackhaulSetting-add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateDialog2" @refreshDataList="getTableList"></dataBackhaulSetting-add-or-update>
		</template>
		<template v-else>
			<div class="d-flex a-center j-center h-100 b-s flex-column">
				<img class="d-flex b-s mt-2 mb-10" src="../../../public/image/download.png" alt="没有访问权限" style="width: 300px;">
				<div class="d-flex">抱歉，您没有访问权限</div>
			</div>
		</template>
	</d2-container>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import mixinViewModule from '@/mixins/view-module'
	import DataBackhaulSettingAddOrUpdate from './dataBackhaulSetting-add-or-update'
	export default {
		mixins: [mixinViewModule],
		components: {
			DataBackhaulSettingAddOrUpdate
		},
		data() {
			return {
				
				tableLoading:false,
				addOrUpdateVisible:false,
				companyName:[],
				appletList:[],
				appletFilters:[],
				templateId:'',
				curent: 0,
				total: 0,
				dataForm: {
					page: 1,
					pageSize: 20,
					keyword:''
				},
				templateForm: {},
				// 增改
				dataList: []
			}
		},
		created() {
			if(this.$hasPermission('playlet:dataBackhaulSetting:index')){
				this.getTableList();
			}
		},
		mounted(){
		},
		watch: {
			dataList:{
				handler(newValue) {
					setTimeout(()=>{
						this.getAppletFilters(this.dataForm.applet_ids,newValue);
					},300)
				},
				deep: true
			},
			templateForm: {
				handler(newValue) {
					console.warn('监听到了');
					this.dataForm = [];
					if(Array.isArray(newValue.convention)){
						if(newValue.convention.length){
							this.dataForm.push(...newValue.convention);
						}
					}
					//超级
					if(Array.isArray(newValue.member)){
						let memberLen = newValue.member.length;
						if(memberLen){
							for (let i = 0; i < memberLen; i++) {
								if(newValue.member[i].status){
									this.dataForm.push(newValue.member[i]);
								}
							}
						}
					}
					//整剧购买
					if(Array.isArray(newValue.promotion)){
						let promotionLen = newValue.promotion.length;
						if(promotionLen){
							for (let i = 0; i < promotionLen; i++) {
								if(newValue.promotion[i].status){
									this.dataForm.unshift(newValue.promotion[i]);
								}
							}
						}
					}
					console.log(this.dataForm);
				},
				deep: true
			}
		},
		computed: {
			...mapState('d2admin/user', [
				'info'
			])
		},
		methods: {
			...mapMutations({
				pageInit: 'd2admin/page/init',
				headerSet: 'd2admin/menu/headerSet'
			}),
			getAppletFilters(applet_id,datalist){
				let anameDom = document.querySelector('.playlet_dataBackhaulSetting_aname span.vxe-cell--filter');
				if(applet_id==1||!applet_id){
					if(Array.isArray(this.info.applet)&&this.info.applet.length){
						this.appletFilters = this.info.applet.filter((item)=>{
							return item.value&&item.value!=1
						})
						if(anameDom&&datalist.length){
							anameDom.style.display = 'inline-block';
						}else{
							anameDom.style.display = 'none';
						}
						return;
					}
				}
				this.appletFilters = [];
				if(anameDom){
					anameDom.style.display = 'none';
				}
			},
			filterApplet ({ option, row }) {
				return row.applet_name == option.label
			},
			clearCompanyFn(){
				this.$set(this.dataForm,'applet_id','');
				this.appletList = [];
			},
			//公司列表
			async companyFocusFn(init=true){
				const companyRes = await this.$axios.get('/api/common/company');
				console.log(companyRes);
				if(Array.isArray(companyRes)){
					if(companyRes.length){
						this.companyName = companyRes;
						return;
					}
				}
				this.companyName = [];
			},
			//小程序列表
			async getAppletFn(){
				const appletRes = await this.$axios.get(`/api/playlet/company/getApplet/${this.dataForm.company_id}`);
				console.log(appletRes);
				if(Array.isArray(appletRes)){
					if(appletRes.length){
						this.appletList = appletRes;
						return;
					}
				}
				this.appletList = [];
			},
			async getTableList(init=false) {
				if(init&&typeof init =='boolean'){
					this.dataForm.page = 1;
				}
				this.tableLoading = true;
				const tableRes = await this.$axios.get('/api/playlet/dataBackhaulSetting?'+this.$qs.stringify(this.dataForm))
				this.tableLoading = false;
				if(typeof tableRes == 'object' && tableRes!=null){
					this.total = tableRes.total||0;
					if(Array.isArray(tableRes.data)){
						let tdlen = tableRes.data.length;
						if(tdlen){
							this.dataList = tableRes.data;
							return
						}
					}
				}
				this.dataList = [];
			},
			//新增/修改弹窗
			async addOrUpdateData(row) {
				console.log(row)
				this.addOrUpdateVisible = true;
				if (typeof row == 'object' && row!=null) {
					const id = row.id;
					const userRes = await this.$axios.get(`/api/playlet/dataBackhaulSetting/update/${id}`,{});
					console.log(257, userRes)
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog.dataId = id;
						this.$refs.addOrUpdateDialog.update(userRes);
					})
				} else {
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog2.dataId = null;
						this.$refs.addOrUpdateDialog2.Applettype = 1;
						this.$refs.addOrUpdateDialog2.init()
					})
				}
			},
			// 删除
			deleteHandleSetter(row) {
				this.$confirm(this.$t('public.prompt.info', {
					handle: this.$t('views.public.delete')
				}), this.$t('public.prompt.title'), {
					confirmButtonText: this.$t('views.public.confirm'),
					cancelButtonText: this.$t('views.public.cancel'),
					type: 'warning'
				}).then(() => {
					this.$axios.delete(`/api/playlet/dataBackhaulSetting/delete/${row.id}`, {}).then(res => {
						this.getTableList();
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 1500,
							onClose: () => {
							}
						})
					}).catch(() => {})
				}).catch(() => {})
			}
		}
	}
</script>

<style lang="scss" scoped>
	:deep(.playlet_dataBackhaulSetting_aname span.vxe-cell--filter){
		display: none;
	}
</style>